<template>
  <div class="order-buy">
    <div class="address-wrap">
      <p class="address-info"><img src="https://img.wifenxiao.com/h5-wfx/images/address_log.png" class="address-icon"/>{{storeAddress}}</p>
      <p v-if="shopName">（{{shopName}}）</p>
    </div>
    <div class="item-block item-block2">
      <div class="item-box">
        <span class="item-title">订单金额（元）</span>
        <div class="item-con">
          <input type="text" class="alignRight" name="money" placeholder="询问服务员后输入" v-model="inputMoney" @input="moneyChange">
        </div>
      </div>
      <div class="item-box">
        <span class="item-title">备注</span>
        <div class="item-con">
          <input type="text" class="alignRight" name="message" placeholder="如服务员号等" v-model="formData.message">
        </div>
      </div>
    </div>
    <!-- 余额，预存款 ， 虚拟库存 ，门店库存 -->
    <div class="item-block item-block2">
      <div class="item-box" v-if="user_balance !=0 && resData.is_open_balance_pay==1" v-show="isShowPayment">
        <van-checkbox class="item-title" v-model="money_type" shape="square" icon-size="14px">
          使用余额
            <i>(余额：<span class="smallsize">{{mSymbol.name}}<b>{{user_balance}}</b></span>)</i>
          <template #icon="props">
            <img class="img-icon" :src="props.checked ? activeIcon : inactiveIcon" />
          </template>
        </van-checkbox>
      </div>

    </div>
    <!-- 其他支付方式 -->
    <div class="item-block item-block2" v-show="isShowOtherPayment">
      <pay-ment
        ref="payments"
        @paymentData="paymentData"
        v-model="paymentWay" :isHffzPay="true"></pay-ment>
    </div>
    <section class="item-block item-block2">
      <!-- 积分抵用 -->
      <section class="item-box" v-if="isShowPoint">
        <span class="item-title">可用{{formData.user_point}}{{resData.point_name}}抵用
          <i class="smallsize">{{mSymbol.name}}<span>{{point_cash_cache}}</span></i>
        </span>
        <section class="item-con">
          <van-switch v-model="is_point_payment"
                      @change="integralChange"
                      class="item-switch"
                      active-color="#EB040B"
                      inactive-color="#F2F2F2"
                      size="15px"/>
        </section>
      </section>
      <!-- 虚拟币抵用 -->
      <section class="item-box" v-if="isShowVirtual">
        <span class="item-title">可用{{formData.user_virtual}}{{resData.virtual_currency_title}}抵用
          <i class="smallsize">&yen;<span>{{virtual_cash_cache}}</span></i>
        </span>
        <section class="item-con">
          <van-switch v-model="is_virtual_payment"
                      @change="virtualChange"
                      class="item-switch"
                      active-color="#EB040B"
                      inactive-color="#F2F2F2"
                      size="15px"/>
        </section>
      </section>
      <section class="money-box">
        <!--总计-->
        <p class="msettlement_intle">
          <span>总计：</span><span class="menoy-num" v-html="scaleGoodsPriceFn(totalPrice)"></span>
        </p>
      </section>
    </section>

    <!-- 支付按钮 -->
    <div class="btn-addorder red-gra-btn" @click="openPayPop">和店员已确认，立即买单</div>
    <!-- 支付密码弹窗 -->
    <pay-password :showPwd="showPwd" @closePwd="closePwd" @payPwdCallback="clickSubmitOrder"></pay-password>
    <!-- 正在支付中 -->
    <div class="paypopnote" v-show="isSubmit"><span>正在提交中……</span></div>
    <!-- 授权弹出框 -->
    <small-login ref="smalllogin"></small-login>
  </div>
</template>

<script>
import { scaleGoodsPrice } from '@/utils/index.js'
import { openPage } from '@/utils/utils.js'
import { isWeixinCient } from '@/utils/validate'
import { storeGathering, storeGatheringAddOrder } from '@/api/order/order.js'
import payMent from '@/components/Payment'
import PayPassword from '@/components/PayPassword/index'
import Vue from 'vue'
import {Checkbox, CheckboxGroup, Toast} from 'vant'
import { Switch, Uploader, Icon } from 'vant'
import { mapGetters } from 'vuex'
import smllpay from '@/smallapp/smallpay'
Vue.use(Checkbox).use(CheckboxGroup)
Vue.use(Switch).use(Uploader).use(Icon)
Vue.use(Toast)
// import SmallLogin from '@/components/SmallLogin/smallLogin.vue'
import small from '@/smallapp/small'
// import { wxSceneExchange } from '@/api/small/login'
export default Vue.extend({
  components: {
    payMent,
    PayPassword
  },
  data() {
    return {
      activeIcon: 'https://img.wifenxiao.com/h5-wfx/images/check_icon.png',
      inactiveIcon: 'https://img.wifenxiao.com/h5-wfx/images/uncheck__icon.png',
      storeAddress: '', // 门店地址
      shopName: '', // 店铺名称
      money_type: false, //  选用余额
      isShowPayment: true,
      isShowOtherPayment: true,
      isShowPoint: 0,
      isShowVirtual: 0,
      paymentWay: '',
      shop_info: {},
      user_balance: '0.00',
      resData: {},
      point_cash_cache: 0, // 积分抵用金额
      virtual_cash_cache: 0, // 虚拟币抵用金额
      inputMoney: '', // 输入框的价格
      totalPrice: '0.00', // 商品总价
      endPrice: '0.00', // 最后需要支付的价格
      formData: {
        self_address_id: '', // 门店id
        type: '', // 用户支付方式
        message: '', // 备注
        payment: '', // 用户支付金额
        is_balance: '', // 是否余额支付
        is_point_payment: '', // 是否积分抵现
        is_virtual_payment: '' // 是否虚拟币抵现
      },
      isSubmit: false,
      is_point_payment: false,
      is_virtual_payment: false,
      showPwd: false, // 支付密码弹框是否显示
      must_pay_password: 0, // 强制输入支付密码
      payData: {}, // 支付相关数据
      remark: -1,
      order_id: 0
    }
  },
  computed: {
    ...mapGetters(['mSymbol'])
  },
  watch: {
    'money_type'(val) {
      if (val) {
        this.formData.money_type = 2
        // 显示余额支付时 如果endPrice大于0则需要显示其他支付方式
        if (this.endPrice <= 0) {
          this.isShowOtherPayment = false
          this.$refs.payments.checkPayment = null
        } else {
          this.isShowOtherPayment = true
          this.$refs.payments.defaultCheckedFn(this.payData)
        }
      } else {
        this.formData.money_type = ''
        this.isShowOtherPayment = true
        this.$refs.payments.defaultCheckedFn(this.payData)
      }
    }
  },
  methods: {
    init() {
      this.getData()
    },
    // 订单金额输入变化
    moneyChange() {
      this.inputMoney = this.onlyNumber(this.inputMoney)
      this.totalPrice = this.inputMoney
      this.reCountPrice()
    },
    // 订单结算
    getData() {
      this.$loadingWrap.show()
      storeGathering({
        self_address_id: this.formData.self_address_id
      }).then(res => {
        this.$loadingWrap.close()
        if (res.status == 1) {
          this.resData = res.data
          const resData = res.data
          this.storeAddress = resData.self_address_info.store_address
          this.shopName = resData.self_address_info.shop_name
          this.isShowPoint = resData.store_point_cash.is_point_cash == 1 && resData.user_can_use_point == 1
          this.isShowVirtual = resData.store_virtual_currency_cash.is_virtual_currency_cash == 1
          this.formData.user_point = resData.user_point // 积分抵用数量
          this.point_cash_cache = resData.user_point * resData.store_point_cash.point_cash / 100// 积分抵用金额
          this.formData.user_virtual = resData.virtual_currency // 虚拟币抵用数量
          this.virtual_cash_cache = resData.virtual_currency * resData.store_virtual_currency_cash.virtual_currency_cash / 100 // 虚拟币抵用金额
          this.formData.point_cash_limit_percent = resData.store_point_cash.point_cash_limit_percent
          this.formData.virtual_cash_max_percent = resData.store_virtual_currency_cash.virtual_cash_max_percent
          this.is_wx_pay_h5 = resData.is_wx_pay_h5
          this.user_balance = resData.user_balance
          this.must_pay_password = resData.must_pay_password // 是否强制输入支付密码
          // 默认勾选余额支付
          if (this.user_balance != 0 && resData.is_open_balance_pay == 1) {
            this.money_type = true
          }
        } else {
          this.$Error(res.msg)
        }
      })
    },
    // 是否显示付款详情
    openPayPop() {
      if (this.paymentWay == 'wxpay') {
        if (isWeixinCient()) { // 微信环境
          this.formData.type = 2
        } else { // 非微信环境
          // 开启了微信h5支付
          if (this.is_wx_pay_h5 == 1) {
            this.formData.type = 12
          }
        }
      } else if (this.paymentWay == 'alipay') {
        this.formData.type = 1
      } else if (this.paymentWay == 'jdpay') {
        this.formData.type = 4
      } else if (this.paymentWay == 'BeiBaopay') {
        this.formData.type = 6
      } else if (this.paymentWay == 'ylpay') {
        this.formData.type = 8
      } else if (this.paymentWay == 'kqpay') {
        this.formData.type = 9
      } else if (this.paymentWay == 'yeepay') {
        this.formData.type = 11
      } else if (this.paymentWay == 'newyeepay') {
        this.formData.newyeepay = 1
        this.formData.type = 14
      } else if (this.paymentWay == 'tlwxpay') { // 通联支付
        this.formData.type = 19
        this.formData.allinpay = 1
      } else if (this.paymentWay == 'hffzWxpay') { // 汇付分账 -- 微信
        this.formData.type = 34
        this.formData.adapay_pay_type = 2
      }
      if (this.money_type) {
        this.formData.money_type = 2
      } else {
        this.formData.money_type = ''
      }
      if (!this.formAuthentication()) return false
      // console.log(this.formData, '>>>>>')
      if ((this.formData.money_type == 2 && this.endPrice <= 0)) { // 余额支付
        // 是否强制使用支付密码
        if (this.must_pay_password == 1) {
          this.$Error('请先去会员中心的修改资料里设置支付密码!')
        } else {
          if (this.formData.money_type == 2 && this.resData.popup_show) {
            this.showPwd = true
          } else {
            this.clickSubmitOrder()
          }
        }
      } else {
        this.clickSubmitOrder()
      }
    },
    // 表单验证
    formAuthentication() {
      let flag = true
      if (!this.inputMoney) {
        this.$Error('请输入订单金额')
        flag = false
      }
      if (this.formData.type == '' && this.formData.money_type == '' && this.isShowPayment && this.resData.is_dhs_send != 1) {
        this.$Error('请选择支付方式')
        flag = false
      }
      return flag
    },
    // 关闭输入支付密码弹窗
    closePwd() {
      this.showPwd = false
    },
    // 提交订单
    clickSubmitOrder() {
      this.isSubmit = true
      const formData = {
        self_address_id: this.formData.self_address_id, // 门店id
        type: this.formData.type, // 用户支付方式
        message: this.formData.message, // 备注
        payment: this.formData.payment, // 用户支付金额
        is_balance: this.money_type ? 1 : 0, // 是否余额支付
        is_point_payment: this.is_point_payment ? 1 : 0, // 是否积分抵现
        is_virtual_payment: this.is_virtual_payment ? 1 : 0, // 是否虚拟币抵现
        adapay_pay_type: this.formData.adapay_pay_type || 0
      }
      // console.log(formData, '11111')
      storeGatheringAddOrder(formData).then(res => {
        this.isSubmit = false
        if (res.status == 1) {
          // 微信支付
            if ((this.formData.type == 2 || this.formData.type == 19 || this.formData.type == 26) && res.data.jsApiParameters) {
              smllpay.wxOrderPay(res.data.jsApiParameters, '', '', true)
            }
            // TODO 跳转
            if (res.data && res.data.redirect_url) {
              setTimeout(() => {
                openPage(res.data.redirect_url)
              }, 1000)
            }

          if (this.formData.type == 34) {
            this.order_id = res.data.order_id
            if (small.wxCache('adapayPlugVersion') == 'jump_adapay_mini') {
              const jsApiParameters = typeof res.data.jsApiParameters === 'object' ? res.data.jsApiParameters : JSON.parse(res.data.jsApiParameters)
              this.hfAppId = jsApiParameters.wx_app_id
              const that = this
              wx.navigateToMiniProgram({
                appId: jsApiParameters.wx_app_id,
                path: jsApiParameters.miniapp_path,
                success(res) {
                  // 打开成功
                  // console.log(res)
                },
                fail(error) {
                  // that.$Error('跳转失败')
                  that.Jump('buySuccess', {id: res.data.order_id})
                }
              })
            } else if (small.wxCache('adapayPlugVersion') == 'self') {
              smllpay.wxOrderPay(res.data.jsApiParameters, '', '', true)
            } else {
              const adapayPlugin = small.wxCache('adapayPlugVersion') == 'new' ? requirePlugin("Adapay") : requirePlugin("adapay-plugin")
              // 汇付分账
              this.isSubmit = false
              // console.log('typeof obj',  typeof res.data.jsApiParameters === 'object')
              const hfPay= res.data.jsApiParameters
              if (hfPay) {
                adapayPlugin.requestPay(hfPay, this.paySuccess, this.payError);
              }
            }
          }
        } else {
          this.$Error(res.msg)
        }
      })
    },
    // 汇付支付成功
    paySuccess() {
      Toast('支付成功！')
      setTimeout(() => {
        this.Jump('/order-lists',{type:6})
      }, 1000)
    },
    // 汇付支付失败
    payError() {
      Toast('支付失败！')
      setTimeout(() => {
        this.Jump('/order-lists',{type:2})
      }, 1000)
    },
    Jump(url, data) {
      this.$JumpPath(this, url, data)
    },
    JumpName(url, data) {
      this.$JumpName(this, url, data)
    },

    JumpUrl(url, data) {
      window.location.href = url
    },
    paymentData(val) {
      // console.log(val, '支付')
      this.payData = val
      setTimeout(() => {
        this.$refs.payments.showHdfkPay = false
        this.$refs.payments.showXxPay = false
        this.$refs.payments.showPeerPal = false
        // 请求数据后 如果有余额则不勾选默认支付方式
        this.money_type ? this.$refs.payments.checkPayment = null : ''
      }, 100)
    },
    scaleGoodsPriceFn(price) {
      return scaleGoodsPrice(price)
    },
    reCountPrice() {
      this.isShowPayment = true
      this.isShowOtherPayment = true
      const resData = this.resData
      let totalPrice = this.totalPrice
      // 积分抵用
      const point_cash = Number(resData.store_point_cash.point_cash)
      // 每次金额发生改变时，需要重新赋值
      this.point_cash_cache = this.resData.user_point * this.resData.store_point_cash.point_cash / 100
      let point_cash_cache = this.point_cash_cache
      let point_cash_limit_percent = resData.store_point_cash.point_cash_limit_percent
      point_cash_limit_percent = point_cash_limit_percent == '0.00' || point_cash_limit_percent == 0 ? 100 : point_cash_limit_percent // 判断积分抵现最高百分比是否为0
      // 虚拟币抵用
      const virtual_cash = Number(resData.store_virtual_currency_cash.virtual_currency_cash)
      const integral_price_virtual = resData.virtual_currency
      let virtual_cash_cache = this.virtual_cash_cache
      let virtual_cash_limit_percent = resData.store_virtual_currency_cash.virtual_cash_max_percent
      virtual_cash_limit_percent = virtual_cash_limit_percent == '0.00' || virtual_cash_limit_percent == 0 ? 100 : virtual_cash_limit_percent // 判断虚拟币抵现最高百分比是否为0

      // 商品可抵现金额随该条件而改变 （当商品积分小于可用积分时）
      if (point_cash != 0) {
        point_cash_cache = totalPrice * (point_cash_limit_percent / 100) * 100 / 100
        const point_val = Math.ceil(point_cash_cache / (point_cash / 100))
        if (point_val <= resData.user_point) {
          point_cash_cache = parseFloat(point_cash_cache.toFixed(2))
        } else {
          point_cash_cache = this.point_cash_cache
          if (parseFloat(totalPrice) < this.point_cash_cache) {
            point_cash_cache = parseFloat(totalPrice)
          }
          if (point_cash_cache < 0) {
            point_cash_cache = 0
          }
          point_cash_cache = parseFloat(point_cash_cache).toFixed(2)
          // point_cash_cache = parseFloat((resData.user_point * (point_cash / 100)).toFixed(2))
        }
      }
      // 判断是否开启抵现取整
      if (resData.store_point_cash.point_is_expense_way != 0) {
        switch (Number(resData.store_point_cash.point_expense_way)) {
          case 1:
            point_cash_cache = Math.ceil(point_cash_cache)
            break
          case 2:
            point_cash_cache = Math.floor(point_cash_cache)
            break
          case 3:
            point_cash_cache = Math.round(point_cash_cache)
            break
        }
      }
      // (1111/(20 / 100))
      this.point_cash_cache = point_cash_cache > 0 ? point_cash_cache : 0
      this.point_cash_cache > resData.store_point_cash.point_cash_limit ? this.point_cash_cache = resData.store_point_cash.point_cash_limit : ''
      this.formData.user_point = Math.ceil(this.point_cash_cache / (point_cash / 100)) > 0 ? Math.ceil(this.point_cash_cache / (point_cash / 100)) : 0
      // 判断是否选用积分抵用
      if (this.is_point_payment) {
        totalPrice = totalPrice - this.point_cash_cache
        if (totalPrice <= 0) {
          this.isShowPayment = false
          this.isShowOtherPayment = false
          this.money_type = true
        }
        this.formData.is_point_payment = 'on'
      } else {
        this.formData.is_point_payment = ''
      }
      this.formData.point_payment = point_cash_cache
      // // console.log(totalPrice, '判断是否开启抵现取整')

      // 虚拟币
      if (virtual_cash != 0) {
        virtual_cash_cache = this.inputMoney * (virtual_cash_limit_percent / 100 * 100) / 100
        virtual_cash_cache = parseFloat(virtual_cash_cache.toFixed(2))
        if (resData.virtual_currency < virtual_cash_cache) {
          virtual_cash_cache = resData.virtual_currency
        }
      }
      if (integral_price_virtual && virtual_cash_cache > integral_price_virtual) {
        virtual_cash_cache = integral_price_virtual
      }
      this.virtual_cash_cache = virtual_cash_cache > 0 ? virtual_cash_cache : 0

      // resData.store_virtual_currency_cash.virtual_currency_cash_limit 为0表示不限制
      resData.store_virtual_currency_cash.virtual_currency_cash_limit > 0 && this.virtual_cash_cache > resData.store_virtual_currency_cash.virtual_currency_cash_limit ? this.virtual_cash_cache = resData.store_virtual_currency_cash.virtual_currency_cash_limit : ''

      this.formData.user_virtual = Math.ceil(this.virtual_cash_cache / (virtual_cash / 100)) > 0 ? Math.ceil(this.virtual_cash_cache / (virtual_cash / 100)) : 0
      // 判断是否选用虚拟币抵用
      if (this.is_virtual_payment) {
        totalPrice = totalPrice - this.virtual_cash_cache
        if (totalPrice <= 0) {
          this.isShowPayment = false
          this.isShowOtherPayment = false
        }
        this.formData.is_virtual_payment = 'on'
      } else {
        this.formData.is_virtual_payment = ''
      }
      this.formData.virtual_payment = virtual_cash_cache
      // // console.log(totalPrice, '判断是否选用虚拟币抵用')

      totalPrice = totalPrice > 0 ? totalPrice : 0

      // 判断是否显示其他支付
      if (this.formData.money_type == '') {
        this.endPrice = totalPrice
      } else if (this.formData.money_type == 2) {
        this.endPrice = Number(totalPrice - this.user_balance).toFixed(2)
        if (this.endPrice <= 0) {
          this.isShowOtherPayment = false
          this.$refs.payments.checkPayment = null
        } else {
          this.$refs.payments.defaultCheckedFn(this.payData)
        }
      }
      this.formData.payment = Number(totalPrice).toFixed(2)
      this.totalPrice = Number(totalPrice).toFixed(2)
      // 输入值为空时还原积分和虚拟币展示数据
      if (!this.inputMoney) {
        this.formData.user_point = resData.user_point // 积分抵用数量
        this.point_cash_cache = resData.user_point * resData.store_point_cash.point_cash / 100// 积分抵用金额
        this.formData.user_virtual = resData.virtual_currency // 虚拟币抵用数量
        this.virtual_cash_cache = resData.virtual_currency * resData.store_virtual_currency_cash.virtual_currency_cash / 100 // 虚拟币抵用金额
      }
    },
    onlyNumber(value) {
      // 先把非数字的都替换掉，除了数字和.
      value = value.replace(/[^\d\.]/g, '')
      // 必须保证第一个为数字而不是.
      value = value.replace(/^\./g, '0.')
      // 保证只有出现一个.而没有多个.
      value = value.replace(/\.{2,}/g, '.')
      // 保证.只出现一次，而不能出现两次以上
      value = value.replace('.', '$#$').replace(/\./g, '').replace('$#$', '.')
      // 只能输入两个小数
      value = value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3')
      return value
    },
    integralChange() {
      if (this.is_point_payment) {
        this.totalPrice = (this.totalPrice * 1 - this.point_cash_cache * 1).toFixed(2)
      } else {
        // 总价大于0时才去计算
        if (Number(this.totalPrice)) {
          this.totalPrice = (this.totalPrice * 1 + this.point_cash_cache * 1).toFixed(2)
        }
      }
      this.totalPrice < 0 ? this.totalPrice = '0.00' : ''
    },
    virtualChange() {
      if (this.is_virtual_payment) {
        this.totalPrice = (this.totalPrice * 1 - this.virtual_cash_cache * 1).toFixed(2)
      } else {
        // 总价大于0时才去计算
        if (Number(this.totalPrice)) {
          this.totalPrice = (this.totalPrice * 1 + this.virtual_cash_cache * 1).toFixed(2)
        }
      }
      this.totalPrice < 0 ? this.totalPrice = '0.00' : ''
    }
  },
  created() {
      this.formData.self_address_id = this.$route.query.self_address_id
      if (small.wxCache('adapayPlugVersion') == 'jump_adapay_mini') {
        this.remark = 1
      }
      this.init()
  },
  mounted() {
      window.addEventListener('wxload', query => {
        // console.log(query, '门店收款码参数')
        // TODO 小程序获取门店id 获取数据
        this.formData.self_address_id = this.$route.query.self_address_id ? this.$route.query.self_address_id : query.self_address_id
        this.init()
      })

      window.addEventListener('wxshow', () => {
        if (!small.checkLogin()) {
          this.$refs.smalllogin.openSmallLoginPop()
        }
        if (small.wxCache('adapayPlugVersion') == 'jump_adapay_mini') {
          let options = wx.getEnterOptionsSync();
          // wx1e18d140f890f2c5，wx308088053f4ecc3a
          if (options.scene == '1038' && options.referrerInfo.appId == this.hfAppId && this.remark == 2) {
            // 代表从收银台小程序返回
            this.Jump('buySuccess', {id: this.order_id})
            // this.isSubmit = false
          }
        }
      })
    if (small.wxCache('adapayPlugVersion') == 'jump_adapay_mini') {
      window.addEventListener('wxHide', () => {
        this.remark = 2
      })
    }
  }
})
</script>

<style lang="scss">
@import "../../../styles/mixin";
@import "src/styles/order/orderBuy";
  .address-wrap {
    padding: 0 24px;
    line-height: 40px;
    margin-bottom: 24px;
    font-size: 28px;
    text-align: center;
    .address-info {
      color: #444;
      font-weight: 400;
    }
    .address-icon {
      width: 28px;
      height: 36px;
      margin-right: 6px;
      vertical-align: middle;
    }
  }
  .price-wrap{
    padding: 40px;
    text-align: center;
    font-size: 28px;
    .price{
      color: #FF0000;
      font-size: 72px;
      margin-top: 30px;
      font-weight: bold;
      .unit{
        font-size: 28px;
        margin-right: 10px;
      }
    }
  }
  .btn-addorder {
    width: 700px;
    height: 92px;
    line-height: 92px;
    color: #fff;
    font-size: 28px;
    font-weight: bold;
    text-align: center;
    border-radius: 92px;
    margin: 0 auto;
  }
  .alignRight {
    text-align: right;
  }
</style>
